import { ref, getCurrentInstance } from "vue";
import { addSubsetApi, getSubsetApi } from "../api/subset_api";
import { getArticleStateApi } from "../api/article_api";
import { getTimeYMDHMS } from "../utils/time";
import { useSubsetStore } from "../stores/subset";
import { useUserStore } from "../stores/user";
import { useCode } from "./codeHook";
import type { articleState } from "../utils/interface";

export function useSubset() {
  const proxy: any = getCurrentInstance()?.proxy;
  const { tackleCode } = useCode();
  const userStore = useUserStore();
  const subsetStore = useSubsetStore();
  //输入框的值
  const inputValue = ref<number | string>();
  //清空输入框
  function cancel() {
    inputValue.value = "";
  }
  //新建分组
  function confirm(e: number) {
    if (inputValue.value) {
      let request = {
        token: userStore.token,
        value: {
          created_at: getTimeYMDHMS(new Date()),
          classify: e,
          subset_name: inputValue.value,
        },
      };
      addSubsetApi(request).then((res: any) => {
        if (tackleCode(res.data.code)) {
          proxy.$message({ type: "primary", message: "新建成功" });
          cancel();
          rawSubset(e);
        }
      });
    } else {
      proxy.$message({ type: "warning", message: "新建失败" });
    }
  }
  //获取分组
  const rawSubset = (e: number) => {
    let request = {
      token: userStore.token,
      classify: e,
    };
    getSubsetApi(request).then((res: any) => {
      if (tackleCode(res.data.code)) {
        let subset = res.data.data;
        subsetStore.data = subset.list;
        subsetStore.count = subset.count;
        getArticleState();
      }
    });
  };

  //获取文章已发布和未发布的状态数量
  const stateCount = ref<Array<articleState>>([]);

  const getArticleState = () => {
    let request = {
      token: userStore.token,
    };
    getArticleStateApi(request)
      .then((res: any) => {
        if (tackleCode(res.data.code)) {
          let count = res.data.data;
          // 创建新数组引用触发响应式更新
          stateCount.value = count;
        }
      })
      // 添加错误处理
      .catch(() => {
        proxy.$message({ type: "error", message: "获取状态数据失败" });
      });
  };
  return {
    rawSubset,
    confirm,
    cancel,
    inputValue,
    getArticleState,
    stateCount,
  };
}
